<script setup>
import { ref } from "vue";
import {
  getAuth,
  createOrder,
  queryUserInfo,
  generate,
  baseUrl,
  validate,
} from "@/api/index.js";
import { showToast } from "vant";
import { onMounted } from "vue";
import { useRoute } from "vue-router";
import list from "./list.vue";
import { showConfirmDialog } from "vant";
import { useCounterStore } from "@/stores/counter";
import toastUrl from "@/assets/toast.png";
// import { wechatConfig } from "@/utils/wechatSdk.js";
// wechatConfig(this);

const store = useCounterStore();
// import TheWelcome from '../components/TheWelcome.vue'
const money = ref(10);
const isShowList = ref(false);
const route = useRoute();
const userCode = ref(null);
const tenantCode = ref(null);
const userInfo = ref(null);
const waterUserInfo = ref(null);
const loading = ref(false);
const showPng = ref(false);
const moneyArr = ref([10, 20, 50, 100, 150, 200]);
// Login();
const submit = async () => {
  if (!money.value) {
    showToast({
      message: "金额不能为空",
      duration: 2000,
    });
  }
  if (!userInfo.value) {
    showToastReg();
    return;
  }
  if (!waterUserInfo.value) {
    showToastRegHot();
    return;
  }
  // 注释白名单
  // let res = await validate({studentId:userInfo.value.number});
  if (res.code != 200) {
    //   showToast({
    //     message: res.message ? res.message : '充值失败，请确认用户信息是否完整！',
    //     duration: 2000,
    //   });
    //   return;
    // }
    let data = {
      orderAmount: money.value,
      phoneNumber: userInfo.value.phone || "",
      studentId: userInfo.value.number || "",
      waterCardNumber: waterUserInfo.value.carPhysicalld || "",
    };
    loading.value = true;
    function generateRandomString(length) {
      const characters =
        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
      let result = "";
      const charactersLength = characters.length;
      for (let i = 0; i < length; i++) {
        result += characters.charAt(
          Math.floor(Math.random() * charactersLength)
        );
      }
      return result;
    }
    createOrder(data).then(async (rs) => {
      if (rs.code == 200 && rs.data) {
        // waterUserInfo.value = rs.data;
        let d = rs.data;
        loading.value = false;
        // d.studentId = 'yktcs001';
        let res = await generate(d);
        if (res.code != 200) {
          showToast({
            message: "请求失败，请重试！",
            duration: 2000,
          });
          return;
        }
        let sign = res.data.sign;
        let t = new Date().getTime();
        let nonce_str = generateRandomString(10);
        // let notify_address = 'https://42984154fw.vicp.fun/payment/notify';
        let notify_address = baseUrl + "/payment/notify";
        // let notify_address = 'https://42984154fw.vicp.fun/payment/notify'
        let redirect_url =
          "https://accommodation-booking-api.sicnu.edu.cn/activityweb/reshui/";
        // let redirect_url = 'https://saas-wap.sicnu.edu.cn/';

        let myapp_id = "101251";
        let sub_openid = userCode.value;
        let subject = "共享吹风机";
        // let href = `https://dev-sicnu-cashier-wap.goliveplus.cn/cashPage?myapp_id=${myapp_id}&out_trade_no=${d.businessOrderNo}&total_amount=${d.orderAmount * 100}&nonce_str=${nonce_str}&sign=${sign}&time_stamp=${t}&auth_code=${d.studentId}&notify_address=${notify_address}&redirect_url=${redirect_url}&sub_openid=${sub_openid}&subject=${subject}&trade_type=jsapi`
        let href = `https://erp-wap.sicnu.edu.cn/cashPage?myapp_id=${myapp_id}&out_trade_no=${
          d.businessOrderNo
        }&total_amount=${
          d.orderAmount * 100
        }&nonce_str=${nonce_str}&sign=${sign}&time_stamp=${t}&auth_code=${
          d.studentId
        }&notify_address=${notify_address}&redirect_url=${redirect_url}&sub_openid=${sub_openid}&subject=${subject}`;

        // https://service.payment.goliveplus.cn

        console.log(href);
        // let href = `https://dev-sicnu-cashier-wap.goliveplus.cn/cashPage?myapp_id=${myapp_id}&out_trade_no=${d.businessOrderNo}&total_amount=${d.orderAmount}&nonce_str=${nonce_str}&sign=${sign}&time_stamp=${t}&auth_code=${d.studentId}&notify_address=${notify_address}&redirect_url=${redirect_url}`
        // let href = `https://erp-wap.sicnu.edu.cn/cashPage?myapp_id=${myapp_id}&out_trade_no=${d.businessOrderNo}&total_amount=${d.orderAmount}&nonce_str=${nonce_str}&sign=${sign}&time_stamp=${t}&auth_code=${d.studentId}&notify_address=${notify_address}&redirect_url=${redirect_url}`
        window.location.href = href;

        return;
      }
      loading.value = false;
    });
  }
  const getHotWaterUser = () => {
    queryUserInfo({
      telPhone: userInfo.value.phone,
    })
      .then((rs) => {
        if (rs.success == true && rs.data) {
          waterUserInfo.value = rs.data;
          loading.value = false;
          return;
        } else {
          showToastRegHot();
        }
        loading.value = false;
      })
      .catch((err) => {
        loading.value = false;
      });
  };
  const showToastRegHot = () => {
    showPng.value = true;
    // showConfirmDialog({
    //   title: '提示',
    //   message:
    //     '暂无热水用户信息，是否前往注册？',
    // })
    //   .then(() => {
    //     // 注册
    //     // window.location.href = "https://saas-wap.sicnu.edu.cn/editPhone"
    //   })
    //   .catch(() => {
    //     // on cancel
    //   });
  };
  const showToastReg = () => {
    showConfirmDialog({
      title: "提示",
      message: "暂无相关用户信息，是否前往注册？",
    })
      .then(() => {
        // 注册
        window.location.href = "https://saas-wap.sicnu.edu.cn/register";
      })
      .catch(() => {
        // on cancel
      });
  };
  const showToastAuth = () => {
    showConfirmDialog({
      title: "提示",
      message: "用户未认证，是否前往认证？",
    })
      .then(() => {
        // 注册
        window.location.href = "https://saas-wap.sicnu.edu.cn/identity";
      })
      .catch(() => {
        // on cancel
      });
  };
  const getAuthRes = () => {
    loading.value = true;
    getAuth({
      encryptionType: "sha1",
      tenantCode: tenantCode.value,
      userCode: userCode.value,
      userType: "weChat",
    })
      .then((rs) => {
        // "status:1未认证 2待审核 3审核通过 4审核不通过;  balance:账户余额; discount:折扣; identity_id:身份id"
        if (rs.code == 200 && rs.data) {
          if (rs.data.status == 1) {
            showToastAuth();
            return;
          }
          userInfo.value = rs.data;
          store.USER_ACTION(userInfo.value);
          getHotWaterUser();
        } else {
          if (rs.code == 500 && !rs.data.length) {
            showToastReg();
          }
          loading.value = false;
        }
      })
      .catch((err) => {
        loading.value = false;
      });
  };
  const editPhone = () => {
    window.location.href = "https://saas-wap.sicnu.edu.cn/editPhone";
  };

  const validateDecimal = (rule, value, callback) => {
    // 使用正则表达式来验证输入是否为最多两位小数的数字
    const regex = /^\d+(\.\d{1,2})?$/;
    if (!regex.test(value)) {
      // 如果验证失败，调用callback并传入错误信息
      callback(new Error("请输入有效的数字，最多两位小数"));
    } else {
      // 如果验证成功，调用callback
      callback();
    }
  };

  // const validator = (v) =>{
  //   return /^(\d+)(\.\d{1,2})?$/.test(v.toString()); //只能输入两个小数
  //   // window.location.href = 'https://saas-wap.sicnu.edu.cn/editPhone'
  // }

  const handleMoney = () => {
    money.value = parseFloat(Number(money.value).toFixed(2));
  };
  onMounted(() => {
    if (store.userCode) {
      userCode.value = store.userCode;
    }
    if (store.tenantCode) {
      tenantCode.value = store.tenantCode;
    }
    // 1获取userCode
    if (route.query) {
      if (route.query.userCode) {
        userCode.value = route.query.userCode;
        store.userCode_ACTION(userCode.value);
      }
      if (route.query.tenantCode) {
        tenantCode.value = route.query.tenantCode;
        store.tenantCode_ACTION(tenantCode.value);
      }
    }
    if (userCode.value && tenantCode.value) {
      getAuthRes();
    }
    // 2 验证
    // 2.1 未注册，跳注册
    // 3 渲染用户数据
  });
};
</script>

<template>
  <van-overlay
    class="flex items-center justify-center"
    :show="showPng"
    @click="showPng = false"
  >
    <van-image width="80vw" :src="toastUrl"> </van-image>
  </van-overlay>
  <van-overlay
    class="flex items-center justify-center"
    :show="loading"
    @click="loading = false"
  >
    <van-loading size="50" color="#1989fa" />
  </van-overlay>
  <div
    style="
      background: linear-gradient(180deg, #2684ff 0%, #f1f3f4 100%);
      height: 40vw;
    "
    class="relative w-screen items-start px-4 pt-4"
  >
    <!-- <img class="top-0 left-0 w-full object-cover" style="height: 100px;"
      src="https://cloudfront.modao.cc/market-template/mt_covers/1/19570/square_cover_1719398519.jpeg" /> -->
    <div class="flex items-center">
      <van-image
        fit="cover"
        width="3.7rem"
        height="3.7rem"
        round
        :src="
          userInfo && userInfo.avatar
            ? userInfo.avatar
            : 'https://fastly.jsdelivr.net/npm/@vant/assets/cat.jpeg'
        "
      >
      </van-image>
      <span class="font-semibold text-xl text-white ml-4">
        欢迎{{ userInfo && userInfo.real_name ? userInfo.real_name : "" }}使用
      </span>
      <div
        v-if="userInfo && userInfo.role"
        style="background: #e4efff; border-radius: 4px; color: #2885ff"
        class="text-sm absolute right-4 px-2 py-1"
      >
        {{ userInfo && userInfo.role ? userInfo.role : "" }}
      </div>
    </div>
  </div>
  <div
    class="bg-white rounded-xl flex-col px-3 py-6 text-base mx-4 relative"
    style="color: #555555; margin-top: -4rem"
  >
    <div class="flex justify-between">
      <!-- <div class="" style="color: #414141;">{{ (userInfo && userInfo.phone) ? userInfo.phone : '' }}</div> -->
      <!-- <div v-if="!isShowList" style="color: #2885FF;" @click="isShowList = true">充值记录</div>
      <div v-else style="color: #2885FF;" @click="isShowList = false">立即充值</div> -->
    </div>
    <div class="flex mt-4">
      <div class="">学工号</div>
      <div class="ml-3">
        {{ userInfo && userInfo.number ? userInfo.number : "" }}
      </div>
    </div>
    <div class="flex justify-between items-center">
      <div class="flex">
        <div>手机号</div>
        <div class="ml-3">
          {{ userInfo && userInfo.phone ? userInfo.phone : "" }}
        </div>
      </div>

      <van-button size="small" type="primary" @click="editPhone"
        >修改</van-button
      >
    </div>
  </div>
  <div class="mt-4 mx-4">
    <van-button
      v-if="isShowList"
      block
      round
      type="primary"
      @click="isShowList = false"
      >立即充值</van-button
    >
  </div>
  <div v-if="!isShowList">
    <div
      class="px-3 py-4 bg-white rounded-xl mt-3 relative flex-col items-center mx-4"
    >
      <div class="mb-4">
        <div class="text-left font-semibold text-base">输入金额</div>
        <van-field
          style="background: #f3f5f9; border-radius: 0.33rem"
          class="mt-4"
          border
          v-model="money"
          type="number"
          placeholder="请输入最多两位小数的数字"
          @blur="handleMoney"
        />
      </div>
      <van-row class="flex justify-between">
        <van-col v-for="item in moneyArr" :key="item" span="7" class="mt-2">
          <div
            :class="money == item ? 'bg2' : 'bg1'"
            class="py-4 text-center w-full"
            style="border-radius: 6px"
            @click="money = item"
          >
            {{ item }}元
          </div>
        </van-col>
      </van-row>
    </div>
    <div class="mt-7 mx-4">
      <van-button v-if="!isShowList" block round type="primary" @click="submit"
        >立即充值</van-button
      >
      <div v-if="!isShowList" class="mt-4">
        <van-button block round type="warning" @click="isShowList = true"
          >充值记录</van-button
        >
      </div>

      <!-- <wx-open-launch-weapp class="opentag" username="wxc077683e930bb81a"
      path="pages/index/index">
    <div v-is="'script'" type='text/wxtag-template'>
         <div>打开小程序</div>
    </div>
</wx-open-launch-weapp> -->
    </div>
    <div style="height: 200px; overflow-y: auto" class="mx-4 my-4 text-sm">
      温馨提示：
      因狮子山部分寝室更换了新的热水淋浴控制器，以下寝室同学需先在川师微生活进行热水淋浴充值，再到热水淋浴小程序使用。
      <br /><span>重德苑2栋：421；</span> <br /><span
        >博学苑3栋：101、102、105、108、110、113、115、116、119、121、206、225、226、224、307、310、311、312、320、401、413、501、502、503、506、508、509、516、517、601、602、603、604、609、610、611、612、616、617；</span
      >
      <br /><span
        >博学苑4栋：101、107、119、205、216、221、223、224、225、226、228、304、326、405、411、414、416、421、424、427、429、509、512、515、522、523、524、525、527、528、601、602、603、609、615、616、618、619、622、623、624、625、627、628、629；</span
      >
      <br /><span
        >尚美苑4栋：113、116、117、119、211、216、217、219、311、313、319、411、413、416、419、511、513、514、516、518、519、616、618、620；</span
      >
      <br /><span
        >尚美苑7栋：416、418、419、420、422、423、424、425、426、427、428、429、502、505、506、507、508、511、513、514、515、520、521、522、524、527、528、529、623、624、625、627、628、629、630；</span
      >
      <br /><span
        >尚美苑8栋：204、206、207、209、210、213、215、216、217、218、219、220、224、226、227、229、231、233、303、306、307、314、317、318、324、326、328、405、412、414、424、429、433、434、504、505、511、512、514、515、516、519、521、523、524、525、527、528、533、534、602、604、605、606、607、610、611、612、613、614、615、616、618、619、620、621、622、623、624、625、626、627、633、634；</span
      >
      <br /><span
        >尚美苑9栋：515、516、519、520、521、522、523、601、603、605、606、607、609、610、611、612、613、614、615、616、617、618、620、621、623；</span
      >
      <br /><span
        >尚美苑10栋：516、517、522、523、524、525、526、528、530、536、601、602、604、605、606、607、608、609、610、611、613、617、628、630；</span
      >
    </div>
    <!-- <div style="color: #9F9F9F;" class="text-center absolute bottom-4 w-screen text-base">
      <span>客户电话：<span class="">0831-21232</span></span>
    </div> -->
  </div>
  <list v-if="isShowList"> </list>
</template>
<style scoped>
.bg1 {
  background: #f3f5f9;
  color: #555555;
}

.bg2 {
  background: #dfedff;
  color: #2885ff;
}
</style>
